package com.kx.yooli.kx.wechat.config.filter;
import com.kx.yooli.kx.wechat.utils.snow.SnowflakeIdWorker;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import java.io.IOException;

/**
 * @author john_sqwen-childe.wen
 * @date 2024/3/28
 * @PROJECT_NAME wechat
 * @description create AbstractTraceIdFilter by john_sqwen
 * and TraceIdfilter value is
 */
public class AbstractTraceIdFilter implements Filter {
    private final Logger log = LoggerFactory.getLogger(AbstractTraceIdFilter.class);

    /**
     * @author :john_sqwen
     * @param traceId
     * @return void
     */
    private void putTraceId(String traceId){
        MDC.put("traceId",traceId);
    }
    /**
     * @author john_sqen
     * @return String traceId
     * @param httpServletRequest
     */
    private String generateTraceId(HttpServletRequest httpServletRequest)   {
        //create id by traceId
        SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(1,1);
        String  traceId = String.valueOf(snowflakeIdWorker.nextId());
        String reqUri= "";
        if (null != httpServletRequest){
            reqUri = httpServletRequest.getRequestURI();
            if(null != reqUri || !reqUri.isBlank()){
                if(reqUri.startsWith("/")){
                    reqUri = reqUri.substring(1);
                }
                if(reqUri.endsWith("/")){
                    reqUri = reqUri.substring(0,reqUri.length()-1);
                }
                reqUri = reqUri.replace("/",".");
            }
        }
        traceId = String.join(">>",traceId,reqUri);
        return traceId;
    }
    /**
     *
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("dfs1231"+filterConfig.getFilterName());
        Filter.super.init(filterConfig);
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //create id by traceId
        String traceId = "";
        try {
            log.info("test host value is {},aaa{}",servletRequest.getRemoteHost(),servletRequest.getProtocol());
            HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
            log.info("change HttpServletRequest type result {}",httpServletRequest);
            traceId = httpServletRequest.getHeader("traceId");
            log.info("front request get traceId value is {}",traceId);
            if(null == traceId || traceId.isBlank()){
                traceId = generateTraceId(httpServletRequest);
                log.info("traceId value is ========{}",traceId);
            }else {
                log.info("obtain traceId[{}] from request header",traceId);
            }
            putTraceId(traceId);
            filterChain.doFilter(servletRequest, servletResponse);
        }finally {
            // must be remove current thread id
            MDC.remove("traceID");
        }
    }
    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
